package com.odm.communitymanage.ui.login

import android.os.Bundle
import android.os.Environment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.blankj.utilcode.util.*
import com.jeremyliao.liveeventbus.LiveEventBus
import com.odm.communitymanage.R
import com.odm.communitymanage.base.BaseMVVMFragment
import com.odm.communitymanage.core.Constants
import com.odm.communitymanage.core.bean.LoginRegisterCallback
import com.odm.communitymanage.core.bean.NetCallBack
import com.odm.communitymanage.core.bean.PostLoginData
import com.odm.communitymanage.core.net.ApiService
import com.odm.communitymanage.ui.HomeFragment
import com.rxjava.rxlife.lifeOnMain
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.fragment_login.*
import rxhttp.wrapper.param.RxHttp
import java.io.File


/**
 * @description: 登录页Fragment,首次登录时自动注册
 * @author: ODM
 * @date: 2020/4/16
 */
class LoginFragment : BaseMVVMFragment() {

    var disposable : Disposable ?= null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        hideBottomNavigation()
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        //销毁请求
        if(false == disposable?.isDisposed){
            disposable?.dispose()
        }
    }

    override fun initViewModelObserve() {

    }

    override fun initViews() {

        tvGetCheckCode.setOnClickListener {
            ToastUtils.showLong("当前为演示模式，验证码为任意数字即可通过")
        }

        /*
         * 登录按钮的点击事件
         */
        btnLogin.setOnClickListener {
            hideSoftInput()
            //先检验手机号是否已经被注册了，已经被注册则直接调用登录，如果没注册则去跳转完善信息
            val phoneNumber : String = etPhone_login?.text.toString()
            if(!RegexUtils.isMobileExact(phoneNumber)){
                ToastUtils.showLong("请输入完整且正确的手机号")
                return@setOnClickListener
            }
            if("" == etCheckCode_login.text.toString()){
                ToastUtils.showLong("密码不可以为空")
                return@setOnClickListener
            }
            RxHttp.get(ApiService.GET_CHECK_CODE + phoneNumber + "/12345")
                .asObject(LoginRegisterCallback::class.java)
                .lifeOnMain(this)
                .subscribe({
                    if(it.code == 1){
                        //已注册了，直接调用登录请求,然后存储返回的小区信息和用户名,身份证件号
                        SPUtils.getInstance(Constants.SP_USER).put(Constants.USER_COMMUNITY_NAME , it.data.villageName)
                        SPUtils.getInstance(Constants.SP_USER).put(Constants.USER_NAME , it.data.name)
                        SPUtils.getInstance(Constants.SP_USER).put(Constants.USER_ID_CARD , it.data.idcard)
                        postLogin(phoneNumber , etCheckCode_login.text.toString())
                    }else{
                        //还没被注册，去完善信息&&帮这个手机号注册
                        val targetFragment = ReplenishInfoFragment()
                        val bundle = Bundle()
                        bundle.putString(Constants.USER_PHONE_NUMBER, etPhone_login.text.toString())
                        bundle.putString(Constants.USER_PASSWORD , etCheckCode_login.text.toString())
                        //为接收方Fragment设置 手机号和密码
                        targetFragment.setArguments(bundle)
                        start(targetFragment)
                        hideSoftInput()
                    }
                },{
                    ToastUtils.showLong(it.message)
                    LogUtils.e(it.message)
                })
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_login
    }

    override fun shouldPopUpCloseDialog(): Boolean {
        return true
    }

    /**
     * 登录请求
     */
    private fun postLogin(phoneNumber:String ,password : String){
        if(phoneNumber == ""|| password == ""){
            ToastUtils.showShort("请填写完整的登录信息")
        }
        disposable = RxHttp.postJson(ApiService.LOGIN)
            .addAll(GsonUtils.toJson(PostLoginData(phoneNumber , password)))
            .asObject(NetCallBack::class.java)
            .lifeOnMain(this)
            .subscribe({
                if(it.code == 1){
                    //登录成功
                    SPUtils.getInstance(Constants.SP_USER).put(Constants.USER_PHONE_NUMBER , phoneNumber)
                    //进入首页
                    enterHome()
                }else {
                    ToastUtils.showLong(it.message)
                }
            },{
                ToastUtils.showLong(it.message)
                LogUtils.e(it.message)
            })



    }

    private fun hideBottomNavigation(){
        LiveEventBus
            .get(Constants.EVENT_HIDE_NAVIGATION)
            .post(Constants.EVENT_HIDE_NAVIGATION)
    }


    /**
     * 进入首页
     */
    private fun enterHome(){
        LiveEventBus
            .get("loadHome")
            .post("loadHome")
        SPUtils.getInstance(Constants.SP_USER).put(Constants.USER_PHONE_NUMBER , etPhone_login.text.toString())
        startWithPop(HomeFragment())
        hideSoftInput()
    }



}
